<!--
 * @Author: OBKoro1
 * @Date: 2022-03-07 10:29:45
 * @LastEditors: OBKoro1
 * @LastEditTime: 2022-10-14 14:47:45
 * @FilePath: \onemodeSWJ\src\views\paramPlanManage\sedParamDataManage\sedParamDataAddCJ.vue
 * @Description: 
 * 
 * Copyright (c) 2022 by 用户/公司名, All Rights Reserved. 
-->
<template>
  <el-table
    style="margin: 10px 0; width: 50%"
    :data="sedData"
    border
    stripe
    size="small"
    :span-method="roughnessTableSpanMethod"
    @cell-mouse-leave="
      (row, column, cell, event) =>
        onMouseleave(row.mainRiverName, row.mainSiteName, row.sectionName)
    "
    @cell-dblclick="
      (row, column, cell, event) =>
        onDblclick(row.mainRiverName, row.mainSiteName, row.sectionName, event)
    "
  >
    <el-table-column
      v-for="item in columns"
      :key="item.dataIndex"
      :label="item.title"
      :width="item.width"
      align="center"
    >
      <template #default="scope">
        <el-input
          v-if="
            scope.row.type != 'title' &&
            editableData[scope.row.mainRiverName][scope.row.mainSiteName][
              scope.row.sectionName
            ][item.dataIndex]
          "
          v-model="
            editableData[scope.row.mainRiverName][scope.row.mainSiteName][
              scope.row.sectionName
            ][item.dataIndex]
          "
          style="margin: -5px 0; text-align: center"
          type="number"
        />
        <div :data-type="item.dataIndex" v-else>
          {{ scope.row[item.dataIndex] }}
        </div>
      </template>
    </el-table-column>
  </el-table>

  <div>
    <el-button
      style="
        position: relative;
        left: 25%;
        transform: translateX(-48%);
        margin-top: 50px;
      "
      type="primary"
      :loading="submitBtnLoadingType"
      @click="submit"
    >
      方案保存
    </el-button>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  provide,
  watch,
  inject,
  reactive,
  toRefs,
  onMounted,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { cloneDeep } from "lodash-es";
import { ElMessage, ElMessageBox } from "element-plus";
import { CloseOutlined, PlusOutlined } from "@ant-design/icons-vue";

import {
  searchNsArgumentsType,
  queryParticlesScheme,
  updateCJParticles,
  queryBedGradationScheme,
} from "@/request/api";

export default defineComponent({
  components: {
    CloseOutlined,
    PlusOutlined,
  },
  setup() {
    const store = useStore();
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      // 方案参数
      planData: {},
      planType: null,

      // 原始数据
      originalData: {},
      // 泥沙参数表格编辑参数
      editableData: {},
      // 泥沙参数数据
      sedData: [],
      // 泥沙参数表头数据
      columns: [],

      // 提交按钮加载状态
      submitBtnLoadingType: false,
    });

    onMounted(() => {
      state.planData = route.params;
      state.planType = route.params.type;

      getNsArgumentsList();
    });

    /**
     * @description: 获取泥沙参数
     * @return {*}
     */
    function getNsArgumentsList() {
      switch (route.params.type) {
        case "csps": // 床沙级配
          getCspsData();
          break;
        case "kms": // 协沙力系数
          getKmsData();
          break;
      }
    }

    /**
     * @description: 干流糙率表格单元格合并
     * @param {*} row 行数据
     * @return {*}
     */
    function roughnessTableSpanMethod({ row }) {
      if (row.type === "title") {
        return {
          rowspan: 1,
          colspan: row.num,
        };
      }
    }

    /**
     * @description: 获取协沙力系数
     * @return {*}
     */
    function getKmsData() {
      queryParticlesScheme({
        particlesId: route.params.id,
        queryType: "2",
      }).then((res: any) => {
        // 原始数据赋值
        state.originalData = res.data;

        // 处理返回JSON字符串数据 以表格数据形式存储
        for (const key in res.data) {
          // 干支流区分（宜昌至大通/洞庭湖区）
          state.editableData[key] = {};

          res.data[key].forEach((item) => {
            // 干支流上站点之间数据（宜昌至城陵矶）
            state.editableData[key][item.mainReachName] = {};

            // 表格数据中新增区域划分
            state.sedData.push({
              sectionName: item.mainReachName,
              type: "title",
              num: 3,
            });

            item.yangtzeParticles.forEach((ele) => {
              // 干支流上站点之间的断面（宜昌站-清江口A1）
              state.editableData[key][item.mainReachName][ele.sectionName] = {};

              // 站点数据新增
              state.sedData.push({
                sectionName: `${ele.sectionName}`,
                type: "data",
                mValue: ele.mValue,
                kValue: ele.kValue,
                mainRiverName: key,
                mainSiteName: item.mainReachName,
                particlesInfoId: ele.particlesInfoId,
              });
            });
          });
        }

        state.columns = [
          {
            title: "站点名",
            dataIndex: "sectionName",
          },
          {
            title: "m值",
            dataIndex: "mValue",
          },
          {
            title: "k值",
            dataIndex: "kValue",
          },
        ];
      });
    }

    /**
     * @description: 获取床沙级配
     * @return {*}
     */
    function getCspsData() {
      queryBedGradationScheme({
        gradationId: route.params.id,
        queryType: "2",
      }).then((res: any) => {});
    }

    /**
     * @description: 根据参数获取数据
     * @param {*} type 参数类型
     * @param {*} value 表格数据
     * @return {*}
     */
    function getRoughnessData(type, value) {
      if (type === "kms") {
        return state.originalData[value.mainRiverName]
          .find((item) => item.mainSiteName === value.mainReachName)
          .yangtzeParticles.find(
            (item) => item.sectionName === value.sectionName
          );
      }
    }

    /**
     * @description: 鼠标双击表格中单元格事件
     * @param {*} mainRiverName 干支流
     * @param {*} mainSiteName 干支流上站点区间
     * @param {*} sectionName 断面
     * @param {*} event 鼠标双击单元格
     * @return {*}
     */
    function onDblclick(mainRiverName, mainSiteName, sectionName, event) {
      // 获取当前参数类型
      const dataType = event.target.getAttribute("data-type");

      if (dataType != "sectionName") {
        // 将参数复制到编辑参数中
        state.editableData[mainRiverName][mainSiteName][sectionName][dataType] =
          getRoughnessData("kms", {
            mainRiverName,
            mainSiteName,
            sectionName,
          })[dataType];
      }
    }

    /**
     * @description: 鼠标移出表格单元格事件
     * @param {*} mainRiverName 干支流
     * @param {*} mainSiteName 干支流上站点区间
     * @param {*} sectionName 断面
     * @return {*}
     */
    function onMouseleave(mainRiverName, mainSiteName, sectionName) {
      // 判断是否为标题
      if (mainRiverName) {
        for (const key in state.editableData[mainRiverName][mainSiteName][
          sectionName
        ]) {
          // 修改已保存的原数据
          getRoughnessData("kms", {
            mainRiverName,
            mainSiteName,
            sectionName,
          })[key] =
            state.editableData[mainRiverName][mainSiteName][sectionName][key];

          getRoughnessData("kms", {
            mainRiverName,
            mainSiteName,
            sectionName,
          }).particlesInfoId = 0;

          // 修改表格数据
          state.sedData.find((item) => item.sectionName === sectionName)[key] =
            state.editableData[mainRiverName][mainSiteName][sectionName][key];
        }

        // 清空当前编辑参数
        state.editableData[mainRiverName][mainSiteName][sectionName] = {};
      }
    }

    /**
     * @description: 保存方案
     * @return {*}
     */
    function submit() {
      switch (route.params.type) {
        case "csps": // 床沙级配
          break;
        case "kms": // 协沙力系数
          updateCJParticles({
            data: state.originalData,
          }).then((res: any) => {
            if (res.code == 200) {
              ElMessage.success(res.msg);

              setTimeout(() => {
                router.push({
                  path: "sedParamDataList",
                  query: {
                    type: route.params.type,
                  },
                });
              }, 1000);
            } else {
              ElMessage.error(res.msg);
            }
          });
          break;
      }
    }

    return {
      ...toRefs(state),

      getNsArgumentsList,
      roughnessTableSpanMethod,
      onDblclick,
      onMouseleave,
      submit,
    };
  },
});
</script>

<style scoped lang="less">
.sedFormInput {
  margin-bottom: 20px;
  .form-box {
    display: flex;
  }
  .el-input {
    width: 100px;
    margin: 0 4px 8px 0;
  }
}
</style>
